package cn.mw.cmdb.config;

import liquibase.Liquibase;
import liquibase.database.DatabaseFactory;
import liquibase.ext.mongodb.database.MongoLiquibaseDatabase;
import liquibase.resource.ClassLoaderResourceAccessor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class LiquibaseConfig implements CommandLineRunner {

    @Value("${spring.data.mongodb.uri}")
    private String databaseUri;


    @Override
    public void run(String... args) throws Exception {
        try {
            MongoLiquibaseDatabase mongoLiquibaseDatabase = (MongoLiquibaseDatabase) DatabaseFactory.getInstance().openDatabase(databaseUri, null,
                    null, null, null);
            Liquibase liquibase = new Liquibase("changelog/changelog-mongodb.json", new ClassLoaderResourceAccessor(), mongoLiquibaseDatabase);
            liquibase.update();
        } catch (Exception e) {
            log.error("run Liquibase error!",e);
        }
    }
}
